package api

import (
	"encoding/json"
	"errors"
	"fmt"
	"hft/tools/phone"
	"hft/tools/phone/model"
	"net/url"
	"strconv"
	"strings"

	"github.com/tidwall/gjson"
)

type Virtual struct{}

func (v *Virtual) AddOrEditPhone(list []*model.Row) (code string) {

	str, _ := json.Marshal(list)

	strJson := string(str)

	var params = &url.Values{
		"data": []string{strJson},
	}

	data := phone.Phone400Api.BaseRequestV2("/addExtensionV2.action", params)
	fmt.Println(string(data), "666")
	res := gjson.Get(string(data), "errcode").String()

	return res
}

// 批量分机查询
func (v *Virtual) FindBatchPhone(pageSize int, pageNow int) *model.Virtual {

	if pageSize <= 0 && pageSize > 5000 {
		pageSize = 100
	}

	if pageNow < 1 {
		pageNow = 1
	}
	var params = &url.Values{
		"pageSize": []string{strconv.Itoa(pageSize)},
		"pageNow":  []string{strconv.Itoa(pageNow)},
	}

	data := phone.Phone400Api.BaseRequestV2("/batchQueryExtensionV2.action", params)

	fmt.Println(string(data))

	var virtual *model.Virtual

	json.Unmarshal(data, &virtual)

	return virtual
}

func (v *Virtual) DeletePhone(dns []string) string {

	data := phone.Phone400Api.BaseRequestV2("/deleteExtensionV2.action", &url.Values{"dn": []string{strings.Join(dns, ",")}})

	errcode := gjson.Get(string(data), "errcode").String()

	return errcode

}

// 查询手机
func (v *Virtual) FirstPhone(dn string) (*model.Row, error) {
	data := phone.Phone400Api.BaseRequestV2("/queryExtensionV2.action", &url.Values{"dn": []string{dn}})
	errcode := gjson.Get(string(data), "errcode").String()
	if errcode == "0" {
		var phone []*model.Row
		row := gjson.Get(string(data), "data").String()
		json.Unmarshal([]byte(row), &phone)
		return phone[0], nil
	} else {
		return nil, errors.New("无法查询")
	}
}

var PhoneVirtual = new(Virtual)
